//
//  HJGroupManagerController.m
//  KaiChat
//
//  Created by lx on 2023/11/14.
//

#import "HJGroupManagerController.h"
#import "HJTitleCell.h"
#import "HJGroupIntroductionCell.h"
#import "HJGroupManagerApprovalCell.h"
#import "HJIM.h"
#import "HJGroupInviteController.h"

@interface HJGroupManagerController ()

@property (nonatomic, strong) NSMutableArray *datas;

@end

@implementation HJGroupManagerController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.title = @"Manage Group";
    
    [self.tableView registerClass:HJGroupManagerApprovalCell.class forCellReuseIdentifier:@"HJGroupManagerApprovalCell"];
    [self.tableView registerClass:HJTitleCell.class forCellReuseIdentifier:@"HJTitleCell"];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    self.tableView.backgroundColor = UIColor.tj_F6F6F6Color;
    self.view.backgroundColor = UIColor.tj_F6F6F6Color;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.right.bottom.offset(0);
    }];
}

- (void)loadData {
    [HJIM.shareIM.groupManager loadGroupInviteCountWithGroupId:self.groupModel.groupId complete:^(NSInteger count) {
        dispatch_async_sql_queue(^{
            HJChatGroupModel *groupModel = [HJIM.shareIM.groupManager queryGroupInfoByGroupId:self.groupModel.groupId];
            self.groupModel.extension = groupModel.extension;
            [self createDataIsReset:YES];
            dispatch_async_main_queue(^{
                [self.tableView reloadData];
            });
        });
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.datas[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJCellModel *model = self.datas[indexPath.section][indexPath.row];
    if ([model.identifier isEqualToString:@"approval"]) {
        HJGroupManagerApprovalCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJGroupManagerApprovalCell" forIndexPath:indexPath];
        cell.model = model;
        TJWeakify(self)
        [cell setSwitchValueChange:^(UISwitch * _Nonnull switchView) {
            [HJIM.shareIM.groupManager openGroupInviteVerifyWithGroupId:weakself.groupModel.groupId open:switchView.isOn completion:^(NSError * _Nullable error) {
                if (error) {
                    switchView.on = !switchView.isOn;
                    return;
                }
                
                weakself.groupModel.openVerify = @(switchView.isOn);
                [weakself.groupModel bg_saveOrUpdateAsync:nil];
                [weakself createDataIsReset:YES];
                [weakself.tableView reloadData];
                
                if (switchView.isOn) {
                    [weakself loadData];
                }
            }];
        }];
        return cell;
    }
    
    if ([model.identifier isEqualToString:@"join"]) {
        HJTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJTitleCell" forIndexPath:indexPath];
        cell.model = model;
        return cell;
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HJCellModel *model = self.datas[indexPath.section][indexPath.row];
    if ([model.identifier isEqualToString:@"notice"]) {
         
        return;
    }
    
    if ([model.identifier isEqualToString:@"join"]) {
        HJGroupInviteController *groupInviteController = [[HJGroupInviteController alloc] init];
        groupInviteController.groupId = self.groupModel.groupId;
        [self.navigationController pushViewController:groupInviteController];
        return;
    }
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    return view;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = UIColor.clearColor;
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJCellModel *model = self.datas[indexPath.section][indexPath.row];
    if (model.height > 0) return model.height;
    return 60;
}

- (void)createDataIsReset:(BOOL)isReset {
    if (isReset) {
        [self.datas removeAllObjects];
    }
    
    [_datas addObject:@[
        [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
        model.text = @"Invitation Approval";
        model.identifier = @"approval";
        model.isOn = self.groupModel.openVerify.intValue == 1;
        model.subText = @"Once enabled, group members need groupowner or group admin approval before they can invite friends to the group. The option to scan QR codes to join the group will be disabled.";
        model.height = 46 + 16 + [[model.subText titleMargin:2 font:UIFontMake(12) alignment:NSTextAlignmentLeft]  boundingRectWithSize:CGSizeMake(KScreenWidth - leftRightMargin * 2, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size.height;
    }]]];
    
    if (_groupModel.openVerify.intValue == 1) {
        [_datas addObject:@[
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
            model.text = @"Join Requests";
            model.identifier = @"join";
            model.showArrow = YES;
            model.textFont = UIFontMediumMake(14);
            NSInteger count = [self.groupModel.extension.mj_JSONObject[groupInviteCountKey] intValue];
            if (count > 0) {
                model.detailText = [NSString stringWithFormat:@"%@", self.groupModel.extension.mj_JSONObject[groupInviteCountKey]];
            } else {
                model.detailText = nil;
            }
        }]]];
    }
    
}

- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}
 
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadData];
}

- (void)dealloc {
    TJLog(@"%s", __func__);
}


@end
